<?php
namespace app\common\model\delivery;


use think\Model;

class DeliveryTpl extends Model
{


    /**
     * 计算运费
     * @param int|string $dispatch_ids 运费模版ID
     * @param array|object $user_address 订单地址信息
     * @param int $num 商品数量
     * @param int|string $weight 商品重量(kg)
    */
    public static function deliveryPrice($dispatch_ids, $user_address, $num, $weight)
    {
        $info = self::where(['id' => $dispatch_ids])->find();
        if($info){
            // 先匹配全国
            $delInfo = DeliveryRule::where('tpl_id','=',$info->id)->find();
            if ($delInfo && $delInfo['area_names'] == '全国') {
                return self::calculate($info->mold,$delInfo->first_price,$delInfo->first_num,$delInfo->rest_price,$delInfo->rest_num,$num,$weight);
            }

            // 再匹配城市
            $delInfo = DeliveryRule::where('tpl_id','=',$info->id)->where('FIND_IN_SET("'.$user_address['city'].'",area_names)')->find();
            if($delInfo){
                return self::calculate($info->mold,$delInfo->first_price,$delInfo->first_num,$delInfo->rest_price,$delInfo->rest_num,$num,$weight);
            }

            // 再匹配省
            $delInfo = DeliveryRule::where('tpl_id','=',$info->id)->where('FIND_IN_SET("'.$user_address['province'].'",area_names)')->find();
            if($delInfo){
                return self::calculate($info->mold,$delInfo->first_price,$delInfo->first_num,$delInfo->rest_price,$delInfo->rest_num,$num,$weight);
            }
        }
        return 0.00;
    }

    /**
     * 价格计算
     * @param int $mold 计费方式:0=重量,1=件数
     * @param float $firstPrice [首件/首重]运费
     * @param int $first_num 首件/首重
     * @param float $restPrice [续件/续重]续费
     * @param int $rest_num 续件/续重
     * @param int $num 商品数量
     * @param float $weight 商品重量(kg)
     */
    public static function calculate($mold, $firstPrice, $first_num, $restPrice, $rest_num, $num, $weight)
    {
        if ($mold == 1) {
            $unit = $num;
        } else {
            $unit = $weight;
        }
        if ($unit > $first_num) {
            $total_restPrice = 0;
            if($rest_num > 0) {
                $total_restPrice = ceil(($unit - $first_num) / $rest_num ) * $restPrice;
            }
            return $firstPrice + $total_restPrice;
        } else {
            return $firstPrice;
        }
    }

    //获取模板列表
    public function getList($shopId){
        $data = $this->where(['shop_id'=>$shopId])->select();
        $newData = [];
        if($data){
            foreach ($data as $k=>$v){
                $newData[$v['id']] = $v['name'];
            }
        }
        return $newData;
    }
}